/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pe.edu.upc.dew.serviciosmultiples.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import pe.edu.upc.dew.serviciosmultiples.exception.DAOException;
import pe.edu.upc.dew.serviciosmultiples.model.Servicio;

/**
 *
 * @author bcano
 */
public class ServicioDAOImpl extends BaseDAO implements ServicioDAO {

    private DataSource dataSource;

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    

    @Override
    public List<Servicio> listarServicios() throws DAOException {
        String query = "select s.idServicio, s.descripcion"
                     + " from servicio s ";
        List<Servicio> lista = new ArrayList<Servicio>();
        Connection con = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            con = dataSource.getConnection();
            stmt = con.prepareStatement(query);
            rs = stmt.executeQuery();
            while (rs.next()) {
                Servicio vo = new Servicio();
                vo.setIdServicio(rs.getInt("idServicio"));
                vo.setDescripcion(rs.getString("descripcion"));
                lista.add(vo);
            }
        } catch (SQLException e) {
            System.err.println(e.getMessage());
            throw new DAOException(e.getMessage());
        } finally {
            this.cerrarResultSet(rs);
            this.cerrarStatement(stmt);
            this.cerrarConexion(con);
        }
        System.out.println("lista de servicios" + lista.size());
        return lista;
    }

}
